<template>
  <div v-loading="true" v-if="loading" class="detail-wapper"/>
  <div v-else class="detail-wapper">
    <el-form ref="ruleForm" :model="formData" :rules="rules" label-width="100px" class="detail-wapper__form">
      <el-form-item label="角色名称" prop="roleName">
        <el-input v-model="formData.roleName" :max-length="10" placeholder="填写账户名称"/>
      </el-form-item>
      <el-form-item label="角色功能" prop="name">
        <el-tree
          ref="functionTree"
          :data="resourceTree"
          :props="defaultProps"
          :default-checked-keys="defaultCheckIds"
          show-checkbox
          default-expand-all
          node-key="resourceCode"
          highlight-current/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm('ruleForm')">保存</el-button>
        <el-button @click="resetForm('ruleForm')">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import { getRoleAllTree, addRole } from '@/api/authManage'
export default {
  name: 'RoleCreate',
  data() {
    return {
      loading: true,
      formData: {
        roleName: ''
      },
      rules: {
        roleName: [
          { required: true, message: '请填写角色名称', trigger: 'blur' }
        ]
      },
      resourceTree: [],
      defaultProps: {
        children: 'children',
        label: 'resourceName'
      },
      defaultCheckIds: []
    }
  },
  async created() {
    this.loading = true
    var getRoleAllTreePromise = getRoleAllTree()
    try {
      const tree = await getRoleAllTreePromise
      this.resourceTree = tree
    } catch (exp) {
      //
    }
    this.loading = false
  },
  methods: {
    _beforeCheck(formName) {
      return new Promise(resolve => {
        this.$refs[formName].validate((valid) => {
          resolve(valid)
        })
      })
    },
    async submitForm(formName) {
      var check = await this._beforeCheck(formName)
      var checkIds = this.getCheckedRescourceIds()
      var {
        roleName = ''
      } = this.formData || {}

      if (check) {
        if (!checkIds || !checkIds.length) {
          this.$message({
            type: 'error',
            message: '请选择角色功能'
          })
          return false
        }
        addRole({ roleName, resources: checkIds.join(',') }, '新建角色失败').then(() => {
          this.$message({
            type: 'success',
            message: '新建角色成功'
          })
          this.$router.replace({ name: 'RoleManage' })
        }).catch(msg => {
          this.$message({
            type: 'error',
            message: msg
          })
        })
      }
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
      this.$refs.functionTree.setCheckedKeys([])
    },
    getCheckedRescourceIds() {
      var { resourceTree = [] } = this
      var childrenCodes = this.$refs.functionTree.getCheckedKeys() || []
      // var parentCodes = childrenCodes.map(code => code.substr(0, 5))
      var ids = []
      childrenCodes.forEach(cCode => {
        var node = resourceTree.find(item => cCode.substr(0, 5) === item.resourceCode)
        if (node) {
          ids.push(node.resourceId)
          var pNode = node.children.find(item => cCode === item.resourceCode)
          if (pNode) {
            ids.push(pNode.resourceId)
          }
        }
      })
      return ids
    }
  }
}
</script>
<style lang="scss" scoped>
.detail-wapper{
    padding:30px;
    &__form{
        width:500px;
        margin:0 auto;
    }
}
</style>
<style lang="scss">
.detail-wapper{
    padding:30px;
    &__form{
        .el-checkbox{
             margin-right:30px;
        }
        .el-checkbox+.el-checkbox{
            margin-left:0;

        }
    }
}
</style>

